//
//  GMAudioView.m
//  Teecloud
//
//  Created by 小熊 on 2018/11/1.
//  Copyright © 2018年 小志. All rights reserved.
//

#import "GMAudioView.h"
#import "GMAudioCell.h"
@interface GMAudioView()<UITableViewDataSource,UITableViewDelegate>
@property (weak, nonatomic) IBOutlet UITableView *tabView;
@property (nonatomic, strong) AVAudioPlayer *player;

@end
@implementation GMAudioView

-(void)awakeFromNib{
    [super awakeFromNib];
    self.tabView.dataSource = self;
    self.tabView.delegate = self;
    self.tabView.separatorStyle = UITableViewCellAccessoryNone;
    [self.tabView registerNib:[UINib nibWithNibName:@"GMAudioCell" bundle:nil] forCellReuseIdentifier:@"GMAudioCell"];
}
-(void)setDataArr:(NSMutableArray *)dataArr{
    _dataArr = dataArr;
    [self.tabView reloadData];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArr.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    GMAudioCell *cell = [tableView dequeueReusableCellWithIdentifier:@"GMAudioCell" forIndexPath:indexPath];
    NSData *voiceData = self.dataArr[indexPath.row];
    NSError *error;
    self.player = [[AVAudioPlayer alloc]initWithData:voiceData error:&error];
    cell.time.text = [self getMMSSFromSS:[NSString stringWithFormat:@"%f",self.player.duration]];
    cell.timeLenth = self.player.duration;
    cell.audioData = voiceData;
    cell.delectBtn.tag =indexPath.row;
    [cell.delectBtn addTarget:self action:@selector(delectAudio:) forControlEvents:UIControlEventTouchUpInside];
    return cell;
}
-(void)delectAudio:(UIButton *)sender{
    NSInteger index = sender.tag;
    [self.dataArr removeObjectAtIndex:index];
    [self.tabView reloadData];
    /**删除音频之后，发送通知刷新录制按钮*/
    [[NSNotificationCenter defaultCenter] postNotificationName:@"updataBtn" object:nil];
}
-(CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 30;
}
//传入 秒  得到  xx分钟xx秒
-(NSString *)getMMSSFromSS:(NSString *)totalTime{
    NSInteger seconds = [totalTime integerValue];
    //format of minute
    NSString *str_minute = [NSString stringWithFormat:@"%ld",seconds/60];
    //format of second
    NSString *str_second = [NSString stringWithFormat:@"%ld",seconds%60];
    //format of time
    NSString *format_time = [NSString stringWithFormat:@"%@′%@″",str_minute,str_second];
    return format_time;
    
}
@end
